package com.molichuxing.services.business;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.HttpClientUtil;
import com.molichuxing.framework.utils.Md5Util;
import com.molichuxing.services.business.dto.response.ViolationBeanDto;
import com.molichuxing.services.business.dto.response.ViolationDataDto;
import com.molichuxing.services.business.dto.response.ViolationDataRecordsDto;
import com.molichuxing.services.business.dto.response.ViolationDto;
import com.molichuxing.services.business.service.ClxBizService;
import com.molichuxing.services.infrastructure.dto.request.create.ThirdViolationLogCreateDto;
import com.molichuxing.services.infrastructure.service.ThirdViolationLogService;

/**
 * 
 * @author liyg
 * 车辆违章实现类
 * 2019-09-17
 *
 */
@Service("clxBizService")
public class ClxBizServiceImpl implements ClxBizService{

	private static Logger logger = Logger.getLogger(ClxBizServiceImpl.class);
	
	@Value("${clx.url}")
	private String clxUrl;
	 
	@Value("${clx.key}")
	private String clxKey;
	
	@Value("${cxy.baseAddress}")
	private String baseAddress;
	
	@Value("${cxy.requestMethod}")
	private String requestMethod;
	
	@Value("${cxy.secretKey}")
	private String secretKey;
	
	@Value("${cxy.appId}")
	private String appId;

//	String baseAddress = "http://test.cx580.com:8311";
//	String requestMethod = "/cxy/viopure/query";
//	String secretKey = "0D28D8869F328CC8E180340BE3DC3F79";
//	String appId = "bjmlcxtest";
	@Resource
	private ThirdViolationLogService thirdViolationLogService;
	
	@Override
	public ResponseResult<List<ViolationBeanDto>> getClxViolation(String licencePlate, String vin, String engineCode) {
		ResponseResult<List<ViolationBeanDto>> responseResult=null;
	    try {
	    	Map<String,String> map=new HashMap<String,String>(5);
			map.put("key", clxKey);
			// 52  小型新能源汽车
			map.put("hpzl", "52");
			map.put("hphm", licencePlate);
			map.put("fdjh", engineCode);
			map.put("cjh", vin);
			String json = HttpClientUtil.doGet(clxUrl, map);
			logger.info("车辆违章返回结果:"+json);
			//记录日志
			ThirdViolationLogCreateDto thirdViolationLogCreateDto  = new ThirdViolationLogCreateDto();
			thirdViolationLogCreateDto.setRequestJson(JSONArray.toJSONString(map));
			if(null != json && !"".equals(json)) {
				thirdViolationLogCreateDto.setResponseJson(json);
			}
			thirdViolationLogService.create(thirdViolationLogCreateDto);
			if(null == json) {
				responseResult = new ResponseResult<List<ViolationBeanDto>>(500,"第三方接口错误（查询车辆违章）") ;
				return responseResult;
			}
			responseResult= convertData(json,licencePlate);
			
		} catch (Exception e) {
			responseResult=new ResponseResult<List<ViolationBeanDto>>(500,"");
		}
		
		return responseResult;
	}

	
	/**
	 * 数据转换
	 * @param json
	 * @return
	 */
	private ResponseResult<List<ViolationBeanDto>> convertData(String json,String licencePlate){
		JSONObject object = JSONObject.parseObject(json);
		ResponseResult<List<ViolationBeanDto>> responseResult=new ResponseResult<List<ViolationBeanDto>>();
		/**
		 *  1001 	key错误或不存在，请检查。 	不计费
		 *	1002 	暂不支持该省查询 	不计费
		 *	1003 	请输入发动机号后 	不计费
		 *	1004 	请输入车架号后 	不计费
		 *	1005 	接口查询条数不足 	不计费
		 *	1006 	交管维护 	不计费
		 *	1007 	车辆信息错误，额外返回errors字段 	不计费
		 *	1008 	有违章 	计费
		 *	1009 	无违章 	计费
		 *	1010 	交管访问超时，请重新尝试 	不计费
		 */
		List<ViolationBeanDto> list=null;
		if(object.getInteger("code")==1008) {
			list=new ArrayList<>();
			JSONArray jsonArray = object.getJSONArray("result");
			for (int i=0;i<jsonArray.size();i++) {
				ViolationBeanDto violationBeanDto = new ViolationBeanDto();
				violationBeanDto.setLicencePlate(licencePlate);
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				if(null != jsonObject.get("wfdz")) {
					violationBeanDto.setAddress(jsonObject.getString("wfdz"));
				}
				if(null != jsonObject.get("wfxw")) {
					violationBeanDto.setRegulationBehavior(jsonObject.getString("wfxw").replace("，",","));
				}
				if(null != jsonObject.get("fkje")) {
					violationBeanDto.setFineFee(jsonObject.getInteger("fkje")+"");
				}
				if(null != jsonObject.get("wfdm")) {
					violationBeanDto.setRegulationCode(jsonObject.getString("wfdm"));
				}
				if(null != jsonObject.get("wzcs")) {
					violationBeanDto.setCityName(jsonObject.getString("wzcs"));
				}
				if(null != jsonObject.get("wfjfs")) {
					violationBeanDto.setRegulationScore(jsonObject.getInteger("wfjfs"));
				}
				//违章处理状态 state 说明    1 未处理未交费    2 已处理未交费  3  已处理已交费
				if(null != jsonObject.get("state")) {
					violationBeanDto.setStatus(jsonObject.getInteger("state"));
				}
				if(null != jsonObject.get("wfsj_date")) {
					LocalDateTime regulationTime = DateUtil.parseDateTime(jsonObject.getString("wfsj_date"));
					violationBeanDto.setRegulationTime(regulationTime);
				}
				if(null != jsonObject.get("clsj")) {
					try {
						violationBeanDto.setHandlingTime(DateUtil.parseDateTime(jsonObject.getString("clsj")));
					} catch (Exception e) {
						
					}
				}
				list.add(violationBeanDto);
			}
			responseResult.setCode(1008);
			responseResult.setData(list);
			return responseResult;
		}else if(object.getInteger("code")==1009){
			responseResult.setCode(1009);
			responseResult.setData(null);
			return responseResult;
		}else if(object.getInteger("code")==500){
			responseResult.setCode(500);
			responseResult.setMessage("第三方车乐行服务异常"+object.get("message"));
			return responseResult;
		}else{
			responseResult.setCode(object.getInteger("code"));
			responseResult.setMessage(object.get("result")+"");
			return responseResult;
		}
		
	}
	
	
	@Override
	public ResponseResult<List<ViolationBeanDto>> getCxyViolation(String licencePlate, String vin, String engineCode) {
		Long timespan = System.currentTimeMillis();
		ResponseResult<List<ViolationBeanDto>> responseResult=null;
		
	try {
			//请求参数
		    Map<String, String> requestMap = new HashMap<>();
		    requestMap.put("carType", "52");
		    requestMap.put("carNumber", licencePlate);
		    vin = vin.substring(vin.length() - 6);
		    requestMap.put("carCode", vin);
		    engineCode =  engineCode.substring(engineCode.length() - 6);
		    requestMap.put("carDriveNumber", engineCode);
		   
		    String sortedStr = vin + engineCode + licencePlate + "52";
		    String concat = timespan.toString().concat(sortedStr).concat(secretKey);
		    String sign = Md5Util.MD5(concat);
		    //发送请求
		    String url = "%s%s?appid=%s&timespan=%s&sign=%s&version=3";
		    url = String.format(url, baseAddress, requestMethod, appId, timespan, sign);
		    Map<String, String> headerMap = new HashMap<>();
		    headerMap.put("Content-Type", "application/json;charset=UTF-8");
	   
			String result = HttpClientUtil.doPost(url, headerMap, requestMap);
			
			//记录日志
			ThirdViolationLogCreateDto thirdViolationLogCreateDto  = new ThirdViolationLogCreateDto();
			thirdViolationLogCreateDto.setRequestJson(JSONArray.toJSONString(requestMap));
			if(StringUtils.isNoneBlank(result)) {
				thirdViolationLogCreateDto.setResponseJson(result);
			}
			thirdViolationLogService.create(thirdViolationLogCreateDto);
			if(StringUtils.isAllBlank(result)) {
				responseResult=new ResponseResult<List<ViolationBeanDto>>(500,"");
			}
			responseResult=convertCxyData(result,licencePlate);
		} catch (Exception e) {
			responseResult=new ResponseResult<List<ViolationBeanDto>>(500,"");
		} 
	    
		return responseResult;
	}
	
	
	private ResponseResult<List<ViolationBeanDto>> convertCxyData(String result,String licencePlate){
		ViolationDto dto = JSONObject.parseObject(result, ViolationDto.class);
		ResponseResult<List<ViolationBeanDto>> responseResult=new ResponseResult<List<ViolationBeanDto>>();
		//80000	查询成功
		if(80000 == dto.getCode()) {
			/**
			 *  车乐行 错误码
			 *  1001 	key错误或不存在，请检查。 	不计费
			 *	1002 	暂不支持该省查询 	不计费
			 *	1003 	请输入发动机号后 	不计费
			 *	1004 	请输入车架号后 	不计费
			 *	1005 	接口查询条数不足 	不计费
			 *	1006 	交管维护 	不计费
			 *	1007 	车辆信息错误，额外返回errors字段 	不计费
			 *	1008 	有违章 	计费
			 *	1009 	无违章 	计费
			 *	1010 	交管访问超时，请重新尝试 	不计费
			 */
			ViolationDataDto data = dto.getData();
			List<ViolationDataRecordsDto> records = data.getRecords();
			//无违章记录
			if(null == records || records.isEmpty()) {
				responseResult.setCode(1009);
				responseResult.setData(null);
				return responseResult;
			}
			
			List<ViolationBeanDto> list = new ArrayList<>();
			for (ViolationDataRecordsDto record : records) {
				ViolationBeanDto beanDto = new ViolationBeanDto();
				beanDto.setLicencePlate(licencePlate);
				beanDto.setRegulationCode(record.getCode());
				beanDto.setRegulationBehavior(record.getReason());
				beanDto.setCityName(record.getLocationName());
				beanDto.setAddress(record.getLocation());
				beanDto.setFineFee(record.getFine());
				if(null != record.getDegree()) {
					beanDto.setRegulationScore(Integer.valueOf(record.getDegree()));
				}
				if(null != record.getTime()) {
					LocalDateTime regulationTime = DateUtil.parseDateTime(record.getTime());
					beanDto.setRegulationTime(regulationTime);
				}
				if(null != record.getStatus()) {
					beanDto.setStatus(Integer.valueOf(record.getStatus()));
				}
				list.add(beanDto);
			}
			responseResult.setCode(1008);
			responseResult.setData(list);
			return responseResult;
		}
		responseResult.setCode(1010);
		responseResult.setData(null);
		responseResult.setMessage(dto.getMsg());
		return responseResult;

	}
}
